
# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# Name:         read_data
# Description:
# Author:       王洪磊
# Email：       wang_hl007@163.com
# Date:         2020/10/26
# 读取微震原始文件
# -------------------------------------------------------------------------------

import pandas as pd
import numpy as np
from pathlib2 import Path


def _str_split(s):
    str_list = list(filter(None, s.split(' ')))
    return str_list


def read_me(path):

    raw_data = pd.read_fwf(path, widths=[6, 10, 10, 10, 10])

    ms_data = raw_data.drop('Unnamed: 0', axis=1)
    return ms_data


def read_bin(file, mode='rb'):
    with open(file, mode) as f:
        d = f.read()
    data = []
    for i in range(128, int(len(d)/4)):
        b_data = d[i*4:i*4+4]
        abs_data = int.from_bytes(b_data[0:2], 'little')
        if b_data[2] % 4 == 0:
            sign = 1
        else:
            sign = -1
        data.append(sign*abs_data)
    data = np.array(data).reshape(-1, 16)
    transform_c = 0.000884393885531461
    ms_data = pd.DataFrame(np.around(data*transform_c, 5), columns=['t'+str(i) for i in range(1, 17)])
    return ms_data


def read_ms(path):
    path = Path(path)
    ms_data = None
    if path.suffix == '.ME':
        ms_data = read_me(path)
    elif path.suffix == '.bin':
        ms_data = read_bin(path)

    return ms_data


def read_wave_data(path, mod='sos'):
    wave_data = None
    if mod == 'sos':
        wave_data  = read_ms(path)
    return wave_data




if __name__ == '__main__':
    # path_bin = r'D:\云空间\程序\0831微震分析系统\resource\sos波形\A01_180803_140014465.bin'
    import matplotlib
    import matplotlib.pyplot as plt
    matplotlib.use('Qt5Agg')


    folder_bin = Path(r'D:\云空间\程序\0831微震分析系统\resource\sos波形')

    paths_bin = [i for i in folder_bin.iterdir() if i.suffix == '.bin']

    for path_bin in paths_bin:
        ms_bin = read_ms(path_bin)
        plt.plot(ms_bin.t2, color='r', linewidth=0.5, label='bin')

        plt.legend()
